#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import random
import uuid
from datetime import datetime, timedelta

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import app, db
from models import Issue, Comment, Tag, Milestone, User, IssueHistory, File
from werkzeug.security import generate_password_hash

# 确保在应用上下文内运行
with app.app_context():
    # 获取已存在的标签
    tags = Tag.query.all()
    print(f"已找到 {len(tags)} 个标签")
    
    # 创建里程碑
    milestones = [
        Milestone(name='v1.0', due_date=datetime.now() + timedelta(days=30)),
        Milestone(name='v1.1', due_date=datetime.now() + timedelta(days=60)),
        Milestone(name='v2.0', due_date=datetime.now() + timedelta(days=90))
    ]
    db.session.add_all(milestones)
    db.session.commit()
    
    # 获取已存在的用户
    users = User.query.all()
    print(f"已找到 {len(users)} 个用户")
    
    # 生成随机日期
    def random_date(start, end):
        return start + timedelta(
            seconds=random.randint(0, int((end - start).total_seconds()))
        )
    
    # 创建问题描述模板
    issue_templates = [
        "系统在点击保存按钮时崩溃，无法保存用户数据。错误日志显示数据库连接超时。",
        "页面加载速度太慢，特别是在移动设备上，需要优化图片加载和JavaScript执行。",
        "用户反馈在使用IE浏览器访问时布局错乱，某些功能按钮不显示。",
        "需要添加数据导出功能，支持CSV和Excel格式，并允许用户自定义导出字段。",
        "搜索功能不够精确，无法找到部分关键词，需要改进搜索算法。",
        "移动端适配问题，在小屏幕设备上菜单显示不正确，按钮太小难以点击。",
        "用户认证系统存在安全漏洞，可能导致未授权访问，需要紧急修复。",
        "需要添加多语言支持，至少包括英文、中文、日语和西班牙语。",
        "数据统计功能不完整，缺少关键指标的图表展示，需要增强数据可视化能力。",
        "系统在高并发情况下响应缓慢，需要优化数据库查询和缓存机制。"
    ]
    
    # 创建评论模板
    comment_templates = [
        "我已经复现了这个问题，确实在特定条件下会出现崩溃。",
        "这个功能很重要，建议优先处理。",
        "我正在修复这个问题，预计今天完成。",
        "已经添加了测试用例，确保问题不会再次出现。",
        "用户反馈很好，这个功能极大提高了工作效率。",
        "需要进一步讨论实现细节，建议召开简短会议。",
        "已经完成代码审查，没有发现明显问题。",
        "这个问题可能与第三方库版本冲突有关，建议检查依赖。",
        "已测试通过，功能符合预期，可以发布。",
        "需要考虑性能优化，当前实现可能在大数据量下有性能问题。"
    ]
    
    # 创建问题
    statuses = ['open', 'closed']
    priorities = ['low', 'medium', 'high', 'urgent']
    categories = ['bug', 'feature', 'task', 'question']
    visibilities = ['public', 'private', 'internal']
    
    issues = []
    for i in range(20):
        # 随机选择用户
        created_by = random.choice(users).id
        assignee_id = random.choice([None] + [user.id for user in users])
        
        # 随机选择里程碑
        milestone_id = random.choice([None] + [milestone.id for milestone in milestones])
        
        # 随机生成日期
        created_at = random_date(datetime.now() - timedelta(days=90), datetime.now())
        updated_at = random_date(created_at, datetime.now())
        due_date = random.choice([None, random_date(datetime.now(), datetime.now() + timedelta(days=60))])
        
        # 创建问题
        issue = Issue(
            title=f"{random.choice(['修复', '添加', '优化', '改进', '解决'])} {random.choice(['系统', '页面', '功能', '模块', 'API'])} {i+1}",
            description=random.choice(issue_templates),
            status=random.choice(statuses),
            priority=random.choice(priorities),
            created_at=created_at,
            updated_at=updated_at,
            due_date=due_date,
            created_by=created_by,
            assignee_id=assignee_id,
            milestone_id=milestone_id,
            category=random.choice(categories),
            visibility=random.choice(visibilities)
        )
        
        # 添加随机标签
        tag_count = random.randint(1, 3)
        selected_tags = random.sample(tags, tag_count)
        for tag in selected_tags:
            issue.tags.append(tag)
        
        issues.append(issue)
    
    db.session.add_all(issues)
    db.session.commit()
    
    # 创建评论
    comments = []
    for issue in issues:
        comment_count = random.randint(0, 5)
        for _ in range(comment_count):
            user = random.choice(users)
            created_at = random_date(issue.created_at, datetime.now())
            
            comment = Comment(
                content=random.choice(comment_templates),
                created_at=created_at,
                user_id=user.id,
                issue_id=issue.id
            )
            comments.append(comment)
    
    db.session.add_all(comments)
    db.session.commit()
    
    # 创建一些模拟文件（不实际保存文件，只创建数据库记录）
    # 确保uploads目录存在
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    
    file_types = [
        ('image/png', 'png', 'image.png'),
        ('image/jpeg', 'jpg', 'photo.jpg'),
        ('video/mp4', 'mp4', 'video.mp4'),
        ('audio/mp3', 'mp3', 'audio.mp3'),
        ('application/pdf', 'pdf', 'document.pdf'),
        ('application/vnd.ms-excel', 'xlsx', 'data.xlsx'),
        ('text/plain', 'txt', 'notes.txt')
    ]
    
    files = []
    # 只为一部分问题添加文件
    issues_with_files = random.sample(issues, int(len(issues) * 0.6))
    
    for issue in issues_with_files:
        file_count = random.randint(1, 3)
        for _ in range(file_count):
            content_type, ext, original_name = random.choice(file_types)
            filename = f"{uuid.uuid4()}.{ext}"
            
            # 创建一个空文件（实际项目中应该使用真实文件）
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            with open(filepath, 'w') as f:
                if content_type.startswith('image/'):
                    f.write('FAKE IMAGE DATA')
                elif content_type.startswith('video/'):
                    f.write('FAKE VIDEO DATA')
                elif content_type.startswith('audio/'):
                    f.write('FAKE AUDIO DATA')
                else:
                    f.write('FAKE FILE DATA')
            
            file_size = os.path.getsize(filepath)
            uploaded_by = random.choice(users).id
            uploaded_at = random_date(issue.created_at, datetime.now())
            
            file = File(
                filename=original_name,
                filepath=filename,
                filetype=content_type,
                filesize=file_size,
                issue_id=issue.id,
                uploaded_by=uploaded_by,
                created_at=uploaded_at
            )
            files.append(file)
    
    db.session.add_all(files)
    db.session.commit()
    
    print(f"已生成虚拟数据：")
    print(f"- {len(tags)} 个标签")
    print(f"- {len(milestones)} 个里程碑")
    print(f"- {len(users)} 个用户")
    print(f"- {len(issues)} 个问题")
    print(f"- {len(comments)} 条评论")
    print(f"- {len(files)} 个文件")
    print("\n用户登录信息：")
    print("- 管理员账号: admin/admin123")
    print("- 其他测试账号: developer1/password1, developer2/password2, tester1/password3, projectmanager/password4")